package com.ruiysoft.crm.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ruiysoft.crm.dto.LoginUser;
import com.ruiysoft.crm.dto.MenuItem;
import com.ruiysoft.crm.dto.SysEmployeeEx;
import com.ruiysoft.crm.dto.SysUserEx;
import com.ruiysoft.crm.entity.Customer;
import com.ruiysoft.crm.entity.SysEmployee;
import com.ruiysoft.crm.entity.SysUser;
import com.ruiysoft.crm.mapper.SysEmployeeMapper;
import com.ruiysoft.crm.mapper.SysPowerMapper;
import com.ruiysoft.crm.mapper.SysUserMapper;
import com.ruiysoft.crm.service.WXBizDataCrypt;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.*;

import static org.springframework.http.HttpHeaders.USER_AGENT;

@RestController
@RequestMapping("/user")
public class SysUserController {
    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysEmployeeMapper sysEmployeeMapper;

    @Autowired
    SysPowerMapper sysPowerMapper;

    @Value("${weixin.appId}")
    String _appId = "";

    @Value("${weixin.secret}")
    String _secret = "";

    String deCodeMobileNu(SysEmployeeEx sysEmployeeEx) {
        WXBizDataCrypt biz = new WXBizDataCrypt(sysEmployeeEx.getAppId(), sysEmployeeEx.getSession_key());
        String rtn = biz.decryptData(sysEmployeeEx.getEncryptedData(), sysEmployeeEx.getIv());
        if(!rtn.startsWith("-4")) {
            JSONObject jsonObject = JSON.parseObject(rtn);
            if(jsonObject != null)
                return jsonObject.getString("phoneNumber");
        }

        return null;

    }

    @PostMapping("createWeixEmployee")
    public Object createWeixEmployee(@RequestBody SysEmployeeEx sysEmployeeEx) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        String _mobile = deCodeMobileNu(sysEmployeeEx);
        if(_mobile == null) {
            map.put("errorMsg", "解密手机号失败");
            return map;
        }

        sysEmployeeEx.setCreateTime(new Date());
        sysEmployeeEx.setMobile(_mobile);
        if(sysEmployeeMapper.insert(sysEmployeeEx) > 0)
            map.put("success", true);

        return map;
    }

    String httpGet(String url) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //默认值我GET
        con.setRequestMethod("GET");

        //添加请求头
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //打印结果
        System.out.println(response.toString());
        return response.toString();

    }

    // "{"nickName":"我是老刘","gender":1,"language":"zh_CN","city":"大兴","province":"北京","country":"中国","avatarUrl":"https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKKMMVoicvTkHwhcEy1kG4LTK6kic4icBNgbrL7GsTARq67cxG51ASR7Ac5JZVqZ63QiaXJKtC5EadpiaA/132"}"
    @GetMapping("queryEmployeeByOpenId")
    public Object queryEmployeeByOpenId(String openId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        SysEmployee sysEmployee = new SysEmployee();
        sysEmployee.setOpenId(openId);
        sysEmployee = sysEmployeeMapper.selectOne(sysEmployee);
        if(sysEmployee != null) {
            map.put("success", true);
            map.put("data", sysEmployee);
        }

        return map;
    }


    @GetMapping("get_openId_sessionKey_unionId")
    public Object get_openId_sessionKey_unionId(String code) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        // https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

        try {
            String rtn = httpGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + _appId + "&secret=" + _secret + "&js_code=" + code + "&grant_type=authorization_code");
            map.put("success", true);
            map.put("data", rtn);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return map;
    }

    @PostMapping("create")
    public Object create(@RequestBody SysUserEx sysUserEx, Integer enterpriseId, Integer departmentId) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            sysUserEx.setCreateTime(new Date());
            sysUserEx.setUpdateTime(new Date());
            sysUserEx.setDeleteFlag(0);
            sysUserEx.setPassword(md5("123456"));

            if (sysUserMapper.insert(sysUserEx) > 0) {
                SysEmployee sysEmployee = new SysEmployee();
                sysEmployee.setUserId(sysUserEx.getId());
                sysEmployee.setCreateTime(new Date());
                sysEmployee.setUpdateTime(new Date());
                sysEmployee.setEnterpriseId(enterpriseId);
                sysEmployee.setDepartmentId(departmentId);
                sysEmployee.setDeleteFlag(0);
                sysEmployee.setMobile(sysUserEx.getMobile());
                sysEmployee.setRoleId(sysUserEx.getRole());
                sysEmployee.setName(sysUserEx.getName());
                sysEmployee.setEmail(sysUserEx.getEmail());

                if(sysEmployeeMapper.insert(sysEmployee) > 0)
                    map.put("success", true);
            }

        } catch (Exception error) {
            map.put("errorMsg", "create 异常: " + error.getMessage());
        }

        return map;
    }

    @GetMapping("delete")
    public Object delete(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            if (sysUserMapper.deleteById(id) > 0)
                map.put("success", true);

        } catch (Exception error) {
            map.put("errorMsg", "delete 异常: " + error.getMessage());
        }

        return map;
    }

    @PostMapping("edit")
    public Object edit(@RequestBody SysUser sysUser) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            if (sysUserMapper.updateById(sysUser) > 0)
                map.put("success", true);
            else
                map.put("errorMsg", "更新失败!");

        } catch (Exception error) {
            map.put("errorMsg", "create 异常: " + error.getMessage());
        }

        return map;
    }

    @Cacheable("query")
    @GetMapping("query")
    public Object query() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);

        try {
            EntityWrapper<SysUser> entityWrapper = new EntityWrapper();
//            List<SysUser> list = sysUserMapper.selectPage(new Page<Customer>(1, 25), entityWrapper);
            List<SysUserEx> list = sysUserMapper.selectAllLeftJoinXXX();
            if(list.size() > 0) {
                map.put("success", true);
                map.put("data", list);
            }
            else
                map.put("errorMsg", "查询数据失败");

        } catch (Exception error) {
            map.put("errorMsg", "delete 异常: " + error.getMessage());
        }

        return map;
    }

    String md5(String pwd) {
        //用于加密的字符
        char md5String[] = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        };
        try {
            //使用平台的默认字符集将此 String 编码为 byte序列，并将结果存储到一个新的 byte数组中
            byte[] btInput = pwd.getBytes();

            //信息摘要是安全的单向哈希函数，它接收任意大小的数据，并输出固定长度的哈希值。
            MessageDigest mdInst = MessageDigest.getInstance("MD5");

            //MessageDigest对象通过使用 update方法处理数据， 使用指定的byte数组更新摘要
            mdInst.update(btInput);

            // 摘要更新之后，通过调用digest（）执行哈希计算，获得密文
            byte[] md = mdInst.digest();

            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {   //  i = 0
                byte byte0 = md[i];  //95
                str[k++] = md5String[byte0 >>> 4 & 0xf];    //    5
                str[k++] = md5String[byte0 & 0xf];   //   F
            }

            //返回经过加密后的字符串
            return new String(str);

        }
        catch (Exception e) {
            return null;
        }
    }

    @Cacheable("login")
    @PostMapping("login")
    public Object login(@RequestBody LoginUser loginUser) {
        Map map = new HashMap();
        map.put("success", false);

        if(loginUser != null) {
            List<SysUser> list = sysUserMapper.selectList(
                    new EntityWrapper<SysUser>()
                            .eq("loginCode", loginUser.getUserName())
                            .eq("password", md5(loginUser.getPassword()))
            );

            if(list.size() > 0) {
                SysUser sysUser = list.get(0);
                List<SysEmployeeEx> list2 = sysEmployeeMapper.selectLeftJoinEnterpriseDepartment(sysUser.getId());
                if(list2.size() > 0) {
                    map.put("success", true);
                    // 一个用户可能有多个企业
                    map.put("infos", list2);
                    map.put("token", "jwt");
                }
                else
                    map.put("errorMsg", "没有查询到对应的员工记录!");
            }
            else
                map.put("errorMsg", "用户名或密码错误!");

//            List<SysPower> list = sysUserMapper.loginAndGetMenuList(loginUser);
//            return list;
        }

        return map;
    }

    @Cacheable("getMenus")
    @GetMapping("getMenus")
    public Object getMenus(Integer roleId) {
        Map map = new HashMap();
        map.put("success", false);

        List<MenuItem> menuList = sysUserMapper.selectMenuListByRoleId(roleId, "0");
        for (MenuItem menuItem: menuList
             ) {
            List<MenuItem> childrenList = sysUserMapper.selectMenuListByRoleId(roleId, menuItem.getCode());
            menuItem.setChildren(childrenList);
        }

        if(menuList != null) {
            map.put("success", true);
            List<MenuItem> wrapList = new ArrayList<MenuItem>();
            MenuItem wrapMenuItem = new MenuItem();
            wrapMenuItem.setChildren(menuList);
            wrapMenuItem.setText("主导航");

            wrapList.add(wrapMenuItem);
            map.put("menu", wrapList);
        }

        return map;
    }
}
